package com.partner.partnerback.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.partner.partnerback.common.Result;
import com.partner.partnerback.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * 文件处理相关接口
 */
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {
    private static final String FILES_DIR = "/files/";

    @Value("${file.upload.path:}")
    private String uploadPath;

    @Value("${server.port:9090}")
    private String serverPort;

    @Value("${file.download.ip:localhost}")
    private String downloadIp;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file){

        String filename = file.getOriginalFilename();//文件完整名称
        String mainName = FileUtil.mainName(filename);//文件主名称
        String extName = FileUtil.extName(file.getOriginalFilename());//文件后缀名
        String uniFileFlag = IdUtil.fastSimpleUUID();
        String fileFullName = uniFileFlag + StrUtil.DOT + extName;
        String fileUploadPath = getFileUploadPath(fileFullName);

        long size = file.getSize();

        String name = file.getName();
        log.info("{},{},{}", filename, size, name);

        try {
            File uploaFile = new File(fileUploadPath);
            File parentFile = uploaFile.getParentFile();
            if (!parentFile.exists()){//如果父级不存在，就要创建
                parentFile.mkdirs();
            }
            file.transferTo(uploaFile);
        } catch (IOException e) {
            log.error("文件上传失败");
            throw new ServiceException("文件上传失败");
        }
        return Result.success("http://"+downloadIp+":" + serverPort + "/file/download/" +fileFullName);

    }

    /**
     * 文件下载
     * @param fileFullName
     * @param response
     * @throws IOException
     */
    @GetMapping("/download/{fileFullName}")
    public void downloadFile(@PathVariable String fileFullName, HttpServletResponse response) throws IOException {

        String extName = FileUtil.extName(fileFullName);
        String fileUploadPath = getFileUploadPath(fileFullName);
        byte[] bytes = FileUtil.readBytes(fileUploadPath);
        response.addHeader("Content-Disposition","inline;filename="+ URLEncoder.encode(fileFullName,"UTF-8"));

        List<String> attachmentFileExtName = CollUtil.newArrayList("docx", "doc", "xlsx", "xls", "mp4", "mp3", "rar", "zip");
        if (attachmentFileExtName.contains(extName)){
            response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileFullName,"UTF-8"));

        }
        OutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();
    }

    /**
     * 获取文件完整路径
     * @param fileFullName
     * @return
     */
    private String getFileUploadPath(String fileFullName){
        if (StrUtil.isBlank(uploadPath)){
            uploadPath = System.getProperty("user.dir");
        }
        return uploadPath + FILES_DIR+fileFullName;
    }

}
